package com.billing.web.controller.administrate;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.billing.model.entity.TManagerPermissions;
import com.billing.model.entity.TManagerPermissionsRelationship;
import com.billing.model.entity.TUser;
import com.billing.service.ManagerPermissionsRelationshipService;
import com.billing.service.ManagerPermissionsService;
import com.billing.service.UserService;
import com.billing.utils.MD5Util;


/**
 * 管理员信息
 * @author Administrator
 *
 */
@RequestMapping(value="/permissions")
@Controller
public class ManagerController {

	
	@Resource
	private ManagerPermissionsService managerPermissionsService;
	@Resource
	private ManagerPermissionsRelationshipService managerPermissionsRelationshipService;
	@Resource
	private UserService userService;
	
	/**
	 * 获取管理员列表
	 * @param request
	 * @param model
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
		String loginname=request.getParameter("loginname");
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int pageSize = 10;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int totalNum = userService.selectTUserLoginnameNum(loginname, organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TUser> list=userService.selectTUserLoginnameList(loginname, organizationid, (currentPage - 1) * pageSize, pageSize);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("totalNum", totalNum);
		request.setAttribute("totalPage", totalPage);
		request.setAttribute("list", list);
		request.setAttribute("loginname", loginname);
		return "permissions/index";
	}
	
//	/**
//	 * 新增管理员
//	 * @param request
//	 * @param model
//	 * @return
//	 * @throws InvocationTargetException 
//	 * @throws IllegalAccessException 
//	 */
//	@RequestMapping(value="/insertmanager",method=RequestMethod.GET)
//	public String insertmanager(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
//		List<TManagerPermissions> mplist=managerPermissionsService.getManagerPermissionsLists();
//		String code="";
//		int i=0;
//		for (TManagerPermissions mp : mplist) {
//			i++;
//			if(i==mplist.size()){
//				code+="{ id:"+mp.getId()+", pId:"+mp.getFatherId()+", name:\""+mp.getName()+"\" ,open:"+mp.isOpen()+"}";
//			}else{
//				code+="{ id:"+mp.getId()+", pId:"+mp.getFatherId()+", name:\""+mp.getName()+"\" ,open:"+mp.isOpen()+"},";
//			}
//		}
//		request.setAttribute("code", code);
//		return "permissions/insert";
//	}
	
//	/**
//	 * 新增管理员
//	 * @param request
//	 * @param model
//	 * @return
//	 * @throws InvocationTargetException 
//	 * @throws IllegalAccessException 
//	 */
//	@RequestMapping(value="/insert",method=RequestMethod.POST)
//	public String insert(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
//		String loginname=request.getParameter("login");
//		String password=request.getParameter("loginpassword");
//		String name=request.getParameter("name");
//		String email=request.getParameter("email");
//		String mobile=request.getParameter("mobile");
//		String status=request.getParameter("status");
//		String powerIds=request.getParameter("powerIds");
//		int organizationid=(int) request.getSession().getAttribute("organizationid");
//		List<TManagerPermissions> mplist=managerPermissionsService.getManagerPermissionsLists();
//		try {
//			password=MD5Util.md5Encode(password);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		ManagerUsersBean managerUsersBean = userService.getUserByNameAndPwd(loginname, password);
//		if(managerUsersBean!=null){
//			request.setAttribute("msg", "该管理员已存在");
//			return "permissions/insert";
//		}
//		ManagerUsersBean mu=new ManagerUsersBean();
//		mu.setLoginname(loginname);
//		mu.setPassword(password);
//		mu.setName(name);
//		mu.setEmail(email);
//		mu.setMobile(mobile);
//		mu.setStatus(Integer.valueOf(status));
//		mu.setCreatetime(System.currentTimeMillis());
//		mu.setOrganizationId(organizationid);
//		managerUsersService.insertManagerUsersBean(mu);
//		List<TManagerPermissionsRelationship> mprlist=new ArrayList<TManagerPermissionsRelationship>();
//		TManagerPermissionsRelationship mpr=null;
//		if(!powerIds.equals("")){
//			String[] powers = powerIds.split(",");
//			for(String ids:powers){
//				int id = 0;
//				try{
//					id =Integer.valueOf(ids);
//				}catch(Exception e){}
//				for (TManagerPermissions mp : mplist) {
//					if(mp.getId()==id){
//						if(mp.getFatherId()==0){
//							mpr=new TManagerPermissionsRelationship();
//							mpr.setPermissionsId(mp.getId());
//							mpr.setUsersId(mu.getId());
//							mprlist.add(mpr);
//							for (TManagerPermissions mpx : mplist) {
//								if(mpx.getFatherId()==mp.getId()){
//									mpr=new TManagerPermissionsRelationship();
//									mpr.setPermissionsId(mpx.getId());
//									mpr.setUsersId(mu.getId());
//									mprlist.add(mpr);
//								}
//							}
//						}else{
//							mpr=new TManagerPermissionsRelationship();
//							mpr.setPermissionsId(mp.getId());
//							mpr.setUsersId(mu.getId());
//							mprlist.add(mpr);
//						}
//					}
//				}
//			}
//		}
//		managerPermissionsRelationshipService.insertTManagerPermissionsRelationship(mprlist);
//		request.setAttribute("msg", "新增管理员成功");
//		return "permissions/insert";
//	}
	
	/**
	 * 修改管理员信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/updatemanager",method=RequestMethod.GET)
	public String updatemanager(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		List<TManagerPermissions> mplist=managerPermissionsService.getManagerPermissionsLists();
		TUser user=userService.selectTUserId(id);
		String code="";
		String powerIds="";
		int i=0;
		int userid = Integer.parseInt(id);
		List<TManagerPermissions> usmpermissions = managerPermissionsService.selectPermissionsById(userid);
		if(user.getMplist()!=null){
			for (TManagerPermissions mp : mplist) {
				for (TManagerPermissions usmp : usmpermissions) {
					if(mp.getId()==usmp.getId()){
						mp.setChecked(true);
						mp.setOpen(true);
						powerIds+=mp.getId()+",";
					}
				}
			}
		}
		for (TManagerPermissions mp : mplist) {
			i++;
			if(i==mplist.size()){
				code+="{ id:"+mp.getId()+", pId:"+mp.getFatherId()+", name:\""+mp.getName()+"\" ,checked:"+mp.isChecked()+" ,open:"+mp.isOpen()+"}";
			}else{
				code+="{ id:"+mp.getId()+", pId:"+mp.getFatherId()+", name:\""+mp.getName()+"\" ,checked:"+mp.isChecked()+" ,open:"+mp.isOpen()+"},";
			}
		}
		if(powerIds.length()>0){
			powerIds=powerIds.substring(0,powerIds.length()-1);
		}
		request.setAttribute("code", code);
		request.setAttribute("user", user);
		request.setAttribute("powerIds", powerIds);
		return "permissions/update";
	}
	
	/**
	 * 修改管理员信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String update(HttpServletRequest request, Model model){
		String userid = request.getParameter("id");
		String loginname=request.getParameter("login");
		String password=request.getParameter("loginpassword");
		String powerIds=request.getParameter("powerIds");
		boolean fal=false;
		TUser user=userService.selectTUserId(userid);
		if(user!=null){
			try {
				if(!password.equals(user.getPassword())){
					password=MD5Util.md5Encode(password);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			user.setLoginname(loginname);
			user.setPassword(password);
			userService.updateTUser(user);
			managerPermissionsRelationshipService.deleteTManagerPermissionsRelationship(user.getId());
			if(powerIds!=null&&!"".equals(powerIds)){
				List<TManagerPermissions> mplist=managerPermissionsService.getManagerPermissionsLists();
				List<TManagerPermissionsRelationship> mprlist=new ArrayList<TManagerPermissionsRelationship>();
				TManagerPermissionsRelationship mpr=null;
				String[] powers = powerIds.split(",");
				for(String ids:powers){
					int id = 0;
					try{
						id =Integer.valueOf(ids);
					}catch(Exception e){}
					for (TManagerPermissions mp : mplist) {
						if(mp.getId()==id){
							if(mp.getFatherId()==0){
								mpr=new TManagerPermissionsRelationship();
								mpr.setPermissionsId(mp.getId());
								mpr.setUsersId(user.getId());
								mprlist.add(mpr);
								for (TManagerPermissions mpx : mplist) {
									if(mpx.getFatherId()==mp.getId()){
										mpr=new TManagerPermissionsRelationship();
										mpr.setPermissionsId(mpx.getId());
										mpr.setUsersId(user.getId());
										mprlist.add(mpr);
									}
								}
							}else{
								mpr=new TManagerPermissionsRelationship();
								mpr.setPermissionsId(mp.getId());
								mpr.setUsersId(user.getId());
								mprlist.add(mpr);
								for (TManagerPermissionsRelationship mprs : mprlist) {
									if(mprs.getPermissionsId()==mp.getFatherId()){
										fal=true;
									}
								}
								if(!fal){
									mpr=new TManagerPermissionsRelationship();
									mpr.setPermissionsId(mp.getFatherId());
									mpr.setUsersId(user.getId());
									mprlist.add(mpr);
									fal=false;
								}
							}
						}
					}
				}
				managerPermissionsRelationshipService.insertTManagerPermissionsRelationship(mprlist);
			}
			request.setAttribute("msg", "修改管理员信息成功");
		}else{
			request.setAttribute("msg", "修改管理员信息失败");
		}
		return "permissions/update";
	}
	
	
//	/**
//	 * 删除管理员
//	 * @param request
//	 * @param model
//	 * @return
//	 * @throws InvocationTargetException 
//	 * @throws IllegalAccessException 
//	 */
//	@RequestMapping(value="/deletemanager",method=RequestMethod.POST)
//	public String deletemanager(HttpServletRequest request, Model model) throws IllegalAccessException, InvocationTargetException{
//		String id = request.getParameter("id");
//		if(id!=null&&id!=""){
//			managerPermissionsRelationshipService.deleteTManagerPermissionsRelationship(Integer.valueOf(id));
//			managerUsersService.deleteManagerUsersBean(Integer.valueOf(id));
//		}
//		return index(request, model);
//	}
}
